package com.kasax.android.arch.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolManager {
    private final ThreadPoolExecutor executor;
    // 当前设备可用处理器核心数*2 + 1,能够让cpu的效率得到最大程度执行
    // 核心线程池的数量，同时能够执行的线程数量
    private final int corePoolSize;
    // 最大线程池数量，表示当缓冲队列满的时候能继续容纳的等待任务的数量
    private final int maximunPoolSize;

    // 自定义线程工厂
    private ThreadFactory myThradFactory = new ThreadFactory() {
        private AtomicInteger threadNum = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "ArchUtilsThread_" + threadNum.incrementAndGet());
            return thread;
        }
    };

    private ThreadPoolManager() {
        /**
         * int codeTaskSize = Runtime.getRuntime().availableProcessors();
         * int maxTaskSize = Math.max(Runtime.getRuntime().availableProcessors() * 2 + 1, mTaskSet.size());
         * int keepAliveTime = 1000;
         * TimeUnit timeUnit = TimeUnit.MILLISECONDS;
         * ArrayBlockingQueue<Runnable> taskBlockingDeque = new ArrayBlockingQueue<>(maxTaskSize - codeTaskSize);
         * defaultThreadPool = new ThreadPoolExecutor(codeTaskSize, maxTaskSize, keepAliveTime, timeUnit,
         * taskBlockingDeque);
         */
        corePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 2;
        maximunPoolSize = corePoolSize;
        executor = new ThreadPoolExecutor(corePoolSize,
                maximunPoolSize,
                60L,  //表示的是maximumPoolSize当中等待任务的存活时间
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), //缓冲队列，用于存放等待任务，Linked的先进先出
//                Executors.defaultThreadFactory(), // 创建线程工厂
                myThradFactory, // 创建线程工厂
                new ThreadPoolExecutor.AbortPolicy() // 用来对超出maximumPoolSize的任务的处理策略
        );
    }

    private static class Holder {
        public static final ThreadPoolManager INSTANCE = new ThreadPoolManager();
    }

    public static ThreadPoolManager getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * 执行任务
     *
     * @param task
     */
    public void execute(Runnable task) {
        if (task == null) {
            return;
        }
        executor.execute(task);
    }

    /**
     * 从线程池中移除任务
     *
     * @param task
     */
    public void remove(Runnable task) {
        if (task == null) {
            return;
        }
        executor.remove(task);
    }


}
